package com.dongdongshop.controller;

import ch.qos.logback.core.encoder.EchoEncoder;
import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.data.HttpResponseEnum;
import com.dongdongshop.data.Result;
import com.dongdongshop.pojo.seller.TbSeller;
import com.dongdongshop.service.SellerServiceI;
import com.dongdongshop.shiro.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("seller")
public class SellerController {

    private final Logger logger= LoggerFactory.getLogger(SellerController.class);

    @Reference
    private SellerServiceI sellerServiceI;

    @RequestMapping("showLogin")
    public String showLogin(){
        return "shoplogin";
    }

    @RequestMapping("toLogin")
    public String toLogin(String sellerId, String password, Model model){
        System.out.println("+++++"+sellerId);
         try {
             Subject subject = SecurityUtils.getSubject();
             UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(sellerId, password);
             subject.login(usernamePasswordToken);
             return "admin/index";
         }catch (UnknownAccountException u){
            model.addAttribute("message","用户不存在");
            return "shoplogin";
         }catch (IncorrectCredentialsException e){
             model.addAttribute("message","密码不正确");
             return "shoplogin";
         }
    }

    @RequestMapping("register")
    public String register(){
        return "register";
    }

    @RequestMapping("toRegister")
    @ResponseBody
    public Result toRegister(TbSeller seller){
        try {
            //撒盐
            String s = ShiroUtils.generateSalt(6);
            seller.setSalt(s);
            //加密文
            String md5 = ShiroUtils.encryptPassword("MD5", seller.getPassword(), s, 3);
            seller.setPassword(md5);
            sellerServiceI.toRegister(seller);
            return Result.jsonResponse(HttpResponseEnum.OK);

        }catch (Exception e){
            logger.error("系统错误",e);
            return Result.jsonResponse(HttpResponseEnum.FAIL);
        }
    }
}
